package com.boot.unity.api.filter;

import com.alibaba.fastjson.JSON;
import com.boot.unity.api.common.ResponseResult;
import com.boot.unity.api.common.Result;
import com.boot.unity.api.common.ResultCodeEnum;
import com.boot.unity.api.constants.Constants;
import com.boot.unity.api.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Order(1)
//@Component
@ConditionalOnProperty(name = "spring.profiles.active",havingValue = "prod")
public class MinutesPeriodFilter extends OncePerRequestFilter {

    @Value("${api.time.scope:5}")
    private int timeScope;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        AntPathMatcher matcher = new AntPathMatcher();
        String uri = request.getRequestURI();
        if (matcher.match(Constants.API_URI_PREFIX,uri)){
            String sts = request.getParameter("ts");
            if (StringUtils.isBlank(sts)){
                log.error("缺少时间参数ts，请求接口：{}，请求IP：{}，请求参数：{}",
                        uri,
                        IpUtil.getIpAddress(request),
                        JSON.toJSONString(request.getParameterMap()));
                Result result = new Result(ResultCodeEnum.DATA_FORMAT_ERROR);
                ResponseResult.toJsonResult(response,result);

            }else {
                long ts = Long.valueOf(sts.trim());
                long cts = System.currentTimeMillis();
                if (Math.abs(cts-ts) > timeScope*60*1000){
                    log.error("ts超过{}分钟时间误差，请求接口：{}，请求IP：{}，请求参数：{}",
                            timeScope,
                            uri,
                            IpUtil.getIpAddress(request),
                            JSON.toJSONString(request.getParameterMap()));
                    Result result = new Result(ResultCodeEnum.TIMESTAMP_REPEAT_OR_ERROR);
                    ResponseResult.toJsonResult(response,result);
                }else {
                    filterChain.doFilter(request,response);
                }
            }
        }else {
            filterChain.doFilter(request,response);
        }
    }
}
